import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hayll_app_village_master/hayll/network/yll_network.dart';
import 'package:hayll_app_village_master/hayll/village_manager/device/device_log_page/bean/device_log.dart';
import 'package:hayll_app_village_master/hayll/village_manager/network/village_action.dart';
import 'package:intl/intl.dart';
import 'action.dart';
import 'state.dart';

Effect<DeviceLogState> buildEffect() {
  return combineEffects(<Object, Effect<DeviceLogState>>{
    DeviceLogAction.action: _onAction,
    DeviceLogAction.getDeviceLog: _getDeviceLog,
    DeviceLogAction.getDeviceLogContent: _getDeviceLogContent,
    Lifecycle.initState: _getDeviceLog,
  });
}

var formatter = DateFormat('yyyy-MM-dd HH:mm:ss');

void _onAction(Action action, Context<DeviceLogState> ctx) {}

//
// termId: "0000a47ff7b3"
// startTime: "2019-12-27 00:00:00"
// endTime: "2019-12-27 17:41:59"

void _getDeviceLog(Action action, Context<DeviceLogState> ctx) {
  var curTime = DateTime.now();
  var endTime = formatter.format(curTime);
  var curStmp = curTime.millisecondsSinceEpoch;
  var currentDateZero =
      curStmp - curStmp % 86400000 - curTime.timeZoneOffset.inMilliseconds;
  int dayNumber = (action.payload != null && action.payload['day'] != null)
      ? action.payload['day']
      : 1;
  var startDateZero = currentDateZero - (dayNumber - 1) * 86400000;
  var startTime =
      formatter.format(DateTime.fromMillisecondsSinceEpoch(startDateZero));
  Map<String, dynamic> params = {
    'termId': (action.payload != null && action.payload['deviceNo'] != null)
        ? action.payload['deviceNo']
        : ctx.state.deviceNo,
    'startTime': '$startTime',
    'endTime': '$endTime'
  };
  YllNetwork.requestPost(VillageAction.getDeviceLog, params: params,
      success: (json) {
    ctx.state.logList.clear();
    var result = DeviceLogListResult.fromJson(json);
    if (result.data != null) {
      ctx.state.logList.addAll(result.data);
    }
    ctx.dispatch(DeviceLogActionCreator.refreshUI());
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _getDeviceLogContent(Action action, Context<DeviceLogState> ctx) {
  DeviceLogResult logInfo = action.payload;
  Navigator.pushNamed(ctx.context, '/device_log_detail', arguments: {
    'url': logInfo.logUrl,
    'time': formatter
        .format(DateTime.fromMillisecondsSinceEpoch(logInfo.createTime))
  });
}
